package com.jaswine.service;


import com.jaswine.bean.po.InfoPO;
import com.jaswine.controller.ClientController;
import com.jaswine.util.JsonUtil;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Component;

import javax.websocket.*;
import javax.websocket.server.ServerEndpoint;

/**
 * 推送Socket
 *
 * @author Jaswine
 */
@ServerEndpoint(value = "/socket/open",encoders = {ServerEncoder.class})
@Slf4j
@Component
public class PushSocketService {

	private Session session;

	private static boolean  f=true;

	private static String heartbeat = "";

	//打开连接执行
	@OnOpen
	public void onOpw(Session session) throws  Exception {
		log.debug("建立连接");
		this.session=session;
		f=true;
		while (f) {

			if(StringUtils.isNotEmpty(heartbeat)){
				//返回心跳给前台
				log.info("hahhah,发送心跳【{}】",heartbeat);
				sendMessage(heartbeat);

				heartbeat = "";
				Thread.sleep(1000);
			}

//			log.info("检测是否为空"+ClientController.infoPOQueue.isEmpty());
			if (!ClientController.infoPOQueue.isEmpty()){
				InfoPO infoPO = ClientController.infoPOQueue.poll();

				log.info("推送数据："+ infoPO.toString());
				sendMessage(infoPO);
				Thread.sleep(100);
			}else{
				//测试数据
			}
			Thread.sleep(100);
		}
	}
	//收到消息执行
	@OnMessage
	public void onMessage(String message,Session session) {
		log.info("收到的消息："+message);
		//前台发送心跳
		if(StringUtils.isNotEmpty(message)){
			heartbeat = message;
		}
	}

	//关闭连接执行
	@OnClose
	public void onClose(Session session)throws Exception {
		session.close();
		log.debug("关闭连接");
	}
	//连接错误的时候执行
	@OnError
	public void onError(Throwable error,Session session) {
		log.info("error");
		error.printStackTrace();
	}


//	private void sendMessage(InfoPO resultInfo) throws Exception {
//		this.session.getAsyncRemote().sendText(JsonUtil.obj2String(resultInfo));
//	}

	private void sendMessage(Object resultInfo) throws Exception {
		this.session.getAsyncRemote().sendText(JsonUtil.obj2String(resultInfo));
	}


}
